package rawengine.timer;


public class TimeHandler {
	
	private static final int MINFRAMEINTERVAL = 5;
	private static final int MAXFRAMEINTERVAL = 50;
	
	private long lastTime;
	private	int timeAcum;
	private	int	frameCount;
	private	int	fps;
	private	boolean preventLowdown;
	private	int frameTime;
	private	float frameTimeSeg;
	
	
	public TimeHandler()
	{
		preventLowdown = true;
		initialize();
	}
	

	public void initialize()
	{
		lastTime  = System.nanoTime();
		frameTimeSeg  = 0.0f;
		frameTime  = 0;
		fps        = 0;
		frameCount = 0;
		timeAcum   = 0;
	}

	public void update()
	{
		frameTime = 0;
		long currentTime;
		
		do
		{
			currentTime	= System.nanoTime();
			if(currentTime >  lastTime)
			{
				frameTime = (int) ((currentTime - lastTime)/1000000);
			}else{
				frameTime = 0;
			}
			
			if(currentTime < lastTime)
			{
				lastTime = currentTime;
			}
			
		}while(!(frameTime >= MINFRAMEINTERVAL));

		if(preventLowdown && (frameTime > MAXFRAMEINTERVAL))
		{
			frameTime = MAXFRAMEINTERVAL;
		}

		timeAcum  += frameTime;
		frameCount++;
		frameTimeSeg = (float)frameTime * 0.001f;

		if(timeAcum >= 1000)
		{
			fps			= frameCount;
			frameCount = 0;
			timeAcum   = 0;
		}

		lastTime = currentTime;
	}

	public long getFrameTime() {
		return frameTime;
	}

	public int getFPS()
	{
		return fps;
	}

	public float getFrameTimeSeg() {
		return frameTimeSeg;
	}


	public void reset()
	{
		lastTime = System.nanoTime();
	}

}
